package cn.goktech.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import cn.goktech.entity.Message;
import cn.goktech.service.IMessageService;
import cn.goktech.service.impl.MessageServiceImpl;

@WebServlet("/MessageServlet")
public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String task=request.getParameter("task");
		
		PrintWriter out = response.getWriter();
		
		IMessageService messageService = new MessageServiceImpl();
		
		if("querymessageList".equals(task)){
			String hostname =request.getParameter("hostname");
			List<Message> messageList = messageService.messageList(hostname);
			if(messageList!=null){
				Gson gson = new Gson();
				String string = gson.toJson(messageList);
				out.print(string);
			}
//			request.setAttribute("messageList", messageList);
//			request.getRequestDispatcher("user/message.jsp").forward(request, response);
		}else if("addmessage".equals(task)){
			String visitorname = request.getParameter("visitorname");
			String hostname =request.getParameter("hostname");
			String content = request.getParameter("content");
			String img =request.getParameter("img");
			Date date = new Date();//获得系统时间.
			
			Message message = new Message();
			message.setHostname(hostname);
			message.setVisitorname(visitorname);
			message.setContent(content);
			message.setImg(img);
			message.setTime(date);
			
			int insertMessage = messageService.insertMessage(message);
			if(insertMessage>0){
				out.write("true");
			} else {
				out.write("false");
			}
			
		}else if("delete".equals(task)){
			int id = Integer.parseInt(request.getParameter("id"));
			
			int deleteMessage = messageService.deleteMessage(id);
			if(deleteMessage>0){
				out.write("true");
			} else {
				out.write("false");
			}
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
